import os
from datetime import datetime
from weibo_scraper import get_weibo_tweets_by_name
from openpyxl import Workbook


def get_weibo_posts(username, year, month):
    # 获取指定月份的微博推文
    posts_generator = get_weibo_tweets_by_name(name=username, pages=None)

    if posts_generator is None:
        raise Exception("未能获取指定用户的推文。")

    # 添加调试输出
    print("Posts generator:", posts_generator)

    # 过滤出指定年份和月份的推文
    year_month_str = f"{year}-{month}"  # Ensure year-month format is correct
    filtered_posts = []
    for post in posts_generator:
        if post and isinstance(post, dict) and 'mblog' in post:
            mblog = post['mblog']
            if 'created_at' in mblog:
                created_at = mblog['created_at']
                # 解析日期并检查是否符合指定的年月
                try:
                    post_date = datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y")
                    if post_date.strftime('%Y-%m') == year_month_str:
                        # 只返回微博内容和发布时间
                        content = post['mblog'].get('text', '')
                        filtered_posts.append((content, post_date))
                except ValueError as e:
                    print(f"Date parsing error: {e}")

    return filtered_posts


def save_to_excel(posts, username, year, month):
    # 创建 Excel 文件
    wb = Workbook()
    ws = wb.active
    ws.title = f"{year}_{month}_Weibo"

    # 写入表头
    ws.append(["发布时间", "内容"])

    # 写入推文
    for post in posts:
        # Format date
        time = datetime.strptime(post['mblog']['created_at'], '%a %b %d %H:%M:%S +0800 %Y').strftime(
            '%Y-%m-%d %H:%M:%S')
        content = post['mblog'].get('text', '')
        ws.append([time, content])

    # 保存文件到 'data' 文件夹中
    if not os.path.exists("../data"):
        os.makedirs("../data")
    wb.save(f"data/{username}_{year}_{month}_weibo.xlsx")
